package red.cyq.modules.filter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thoughtworks.xstream.mapper.Mapper.Null;

import red.cyq.modules.entity.User;

public class MyFilter implements javax.servlet.Filter {
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
		Logger logger = LoggerFactory.getLogger(getClass());
		// ����Connection����
		Connection con;
		// ����������
		String driver = "com.mysql.jdbc.Driver";
		// URLָ��Ҫ���ʵ����ݿ���mydata
		String url = "jdbc:mysql://qdm21395091.my3w.com:3306/qdm21395091_db?useUnicode=true&amp;characterEncoding=utf-8&amp;zeroDateTimeBehavior=convertToNull&amp;allowMultiQueries=true";
		// MySQL����ʱ���û���
		String user = "qdm21395091";
		// MySQL����ʱ������
		String password = "kk5201314";
		try {
//			logger.warn("----------------------��ʼ�������ݿ�����");
//			Class.forName(driver);
//			con = DriverManager.getConnection(url,user, password);
//			PreparedStatement  pre = con.prepareStatement("select * from message");
//			ResultSet result = pre.executeQuery();
//			
//			
//			System.out.println(result);
//			System.out.println(con);
//			logger.warn("----------------------" , "���ݿ�����" + con);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String remoteAddr = req.getRemoteAddr() + ":" + req.getRemoteHost() + ":" + req.getRemotePort();
		if (isStatic(req.getRequestURI())) {
			chain.doFilter(request, response);
			return;
		}
		if (isRelease(req.getRequestURI())) {
			chain.doFilter(request, response);
			return ; 
		}
		if(req.getSession().getAttribute(User.USER_SESSION) == null) {
			resp.sendRedirect("/tologin");
		}
		chain.doFilter(request, response);
	}

	private boolean isRelease(String requestURI) {
		String[] arr = {"login", "tologin", "favicon.ico"};
		for (String s : arr) {
			if (requestURI.indexOf(s) > -1) {
				return true;
			}
		}
		return false;
	}

	private boolean isStatic(String requestURI) {
		String[] arr = {".jpg", ".png", ".css", ".js", ".ioc"};
		for (String s : arr) {
			if (requestURI.endsWith(s)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
